package com.demo.config.sharding;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 * 精确分片
 * @author: cyj
 **/
@Slf4j
public class PreciseShardingStrategy implements PreciseShardingAlgorithm<Long> {

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
        log.info("精确分片，表:{}，ShardingValue:{}", availableTargetNames, shardingValue);
        Long value = shardingValue.getValue();
        long mod = value % ShardingConstant.DB_NUM;
        for (String dbName : availableTargetNames) {
            if (StringUtils.equals(dbName, ShardingConstant.DB_NAME + mod)) {
                return dbName;
            }
        }
        return StringUtils.EMPTY;
    }
}
